var app = getApp();
Page({
  data: {
    villageList: [], //园区列表
    searchName: '', //搜索园区名
    village: {},
    location: {},
    empty: false,
    villageIndex: "", //选中园区的index
  },
  onLoad: function (options) {
    this.from = options.from || 1;
    let _self = this;
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      _self.getVillage(data.village_id);
    })
  },

  addVillage() {
    wx.navigateTo({
      url: '../editCommunity/editCommunity?type=2',
    })
  },


  /**
   * 获取园区列表
   */
  getVillage(id) {
    var that = this;
    let url = "Partner/WaterCard/getPartnerVillage";
    if (this.from != 1) {
      url = "Salesman/Card/getPartnerVillage";
    }
    app.ajax({
      url,
      data: {
        village_name: that.data.searchName,
        lat: that.data.location.lat,
        lng: that.data.location.lng,
      },
      success: function (res) {
        if (res.data.code == 1000) {
          let villageList = res.data.data;
          villageList.unshift({
            id: "",
            village_name: "",
            province: "",
            city: "",
            area: "",
            address:''
          });
          let index = villageList.findIndex(item => item.id == id)
          if (villageList.length > 0) {
            that.setData({
              villageList: villageList,
              villageIndex: ~index ? index : 0,
              empty: false
            });
            that.orignList = JSON.parse(JSON.stringify(villageList));
          } else {
            that.setData({
              empty: true
            })
          }
        }
      }
    })
  },

  //搜索园区
  searchName(e) {
    const val = e.detail.value;
    const list = this.orignList;
    if (list.length <= 0) {
      return false;
    }
    const results = list.filter(current => {
      let str = [current.province_name, current.city_name, current.area_name, current.address].join('');
      return str.includes(val) || current.village_name.includes(val)
    })
    this.setData({
      searchName: val,
      villageList: results
    })

  },
  //选择园区
  chooseVillage(e) {
    const {
      index,
      village
    } = e.currentTarget.dataset;

    this.setData({
      village,
      villageIndex: index
    })
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('acceptDataFromOpenedPage', {
      ...village
    });
    setTimeout(() => {
      wx.navigateBack({
        delta: 1
      })
    }, 500)

  },
  //获取当前位置
  getLocation() {
    var that = this;
    wx.getLocation({
      success: function (res) {
        let location = {}
        location.lat = res.latitude;
        location.lng = res.longitude;
        that.setData({
          location: location
        })
        that.getVillage();
      },
      fail: function () {
        app.showToast('很抱歉,无法获取您的位置,请返回重试!');
      }
    })
  },
  getRad(d) {
    var PI = Math.PI;
    return d * PI / 180.0;
  },

  /**
   * 获取两个经纬度之间的距离
   * @param lat1 第一点的纬度
   * @param lng1 第一点的经度
   * @param lat2 第二点的纬度
   * @param lng2 第二点的经度
   * @returns {Number}
   */
  getDistance(lat1, lng1, lat2, lng2) {
    var f = this.getRad((lat1 + lat2) / 2);
    var g = this.getRad((lat1 - lat2) / 2);
    var l = this.getRad((lng1 - lng2) / 2);
    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);
    var s, c, w, r, d, h1, h2;
    var a = 6378137.0; //The Radius of eath in meter.   
    var fl = 1 / 298.257;
    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;
    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;
    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;
    s = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
    s = s / 1000;
    s = s.toFixed(2); //指定小数点后的位数。   
    return s;
  },





  //计算距离
  calculateDistance(Vlatitude, Vlongitude) {
    var that = this;
    MapWXsap.calculateDistance({
      from: {
        latitude: that.data.location.lat,
        longitude: that.data.location.lng
      },
      to: [{
        latitude: Vlatitude,
        longitude: Vlongitude
      }],
      success: function (res) {
        console.log(res.result.elements[0].distance);
        let distance = res.result.elements[0].distance;
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  }
})